// src/utils/editor-menus.ts - 简化版本
import { Boot, IButtonMenu } from '@wangeditor/editor'
import cache from '@/utils/cache'

class AttachmentMenu implements IButtonMenu {
    readonly title = '上传附件'
    readonly iconSvg = '<svg viewBox="0 0 1024 1024"><path d="M832 64H192c-17.7 0-32 14.3-32 32v832c0 17.7 14.3 32 32 32h640c17.7 0 32-14.3 32-32V96c0-17.7-14.3-32-32-32z m-40 824H232V136h560v752z"/><path d="M640 384H384c-17.7 0-32 14.3-32 32s14.3 32 32 32h256c17.7 0 32-14.3 32-32s-14.3-32-32-32zM640 544H384c-17.7 0-32 14.3-32 32s14.3 32 32 32h256c17.7 0 32-14.3 32-32s-14.3-32-32-32z"/></svg>'
    readonly tag = 'button'

    getValue() { return '' }
    isActive() { return false }
    isDisabled() { return false }

    exec(editor: any) {
        const input = document.createElement('input')
        input.type = 'file'
        input.accept = '*/*'

        input.onchange = async (e) => {
            const file = (e.target as HTMLInputElement).files?.[0]
            if (!file) return

            await this.uploadAndInsert(editor, file)
        }

        input.click()
    }

    async uploadAndInsert(editor: any, file: File) {
        try {
            // 显示简单的加载提示
            this.showTempMessage('上传中...', 'info')

            const formData = new FormData()
            formData.append('file', file)

            const uploadApi = import.meta.env.VITE_API_URL + '/content/upload'
            const token = cache.getToken()

            const response = await fetch(uploadApi, {
                method: 'POST',
                headers: {
                    'Authorization': token,
                    'Accept': 'application/json, text/plain, */*'
                },
                body: formData
            })

            const result = await response.json()


            this.insertFile(editor, file, result.data.url)
            this.showTempMessage('文件上传成功', 'success')
        } catch (error) {
            this.showTempMessage('上传失败', 'error')
            console.error('上传错误:', error)
        }
    }

    insertFile(editor: any, file: File, fileUrl: string) {
        const fileName = file.name
        const fileHtml = `
      <div style="margin: 10px 0; padding: 12px; border: 1px solid #e1e1e1; border-radius: 6px; background: #f9f9f9;">
        <a href="${fileUrl}" target="_blank" style="display: flex; align-items: center; text-decoration: none; color: #1890ff;">
          <div style="flex: 1;">
            <div style="font-weight: 500;margin-right:8px;">可下载附件：</div>
            <div style="font-weight: 500;">${fileName}</div>
          </div>
        </a>
      </div>
    `

        editor.focus()
        editor.dangerouslyInsertHtml(fileHtml)
    }

    formatFileSize(bytes: number): string {
        if (bytes === 0) return '0 B'
        const k = 1024
        const sizes = ['B', 'KB', 'MB', 'GB']
        const i = Math.floor(Math.log(bytes) / Math.log(k))
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    showTempMessage(message: string, type: 'success' | 'error' | 'info' = 'success') {
        // 创建临时消息元素
        const messageElement = document.createElement('div')
        const bgColor = type === 'success' ? '#67c23a' :
            type === 'error' ? '#f56c6c' : '#909399'

        messageElement.style.cssText = `
      position: fixed;
      top: 20px;
      right: 20px;
      padding: 12px 20px;
      border-radius: 4px;
      color: white;
      background: ${bgColor};
      z-index: 9999;
      max-width: 300px;
      word-wrap: break-word;
      font-family: system-ui, -apple-system, sans-serif;
    `
        messageElement.textContent = message
        document.body.appendChild(messageElement)

        // 3秒后自动移除
        setTimeout(() => {
            if (document.body.contains(messageElement)) {
                document.body.removeChild(messageElement)
            }
        }, 3000)
    }
}

// 全局注册
let isRegistered = false

export function registerEditorMenus() {
    if (!isRegistered) {
        Boot.registerMenu({
            key: 'uploadAttachment',
            factory: () => new AttachmentMenu()
        })
        isRegistered = true
        console.log('自定义编辑器菜单已注册')
    }
}